//
//  CoachVideoViewController.m
//  CoollangTennisBall
//
//  Created by Coollang on 2017/8/26.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "CoachVideoViewController.h"
#import "CoachVideo.h"
#import "CoachVideoCell.h"
#import "UIView+Frame.h"
#import "PlayVideoViewController.h"


CGFloat const HeaderHeight = 25;
CGFloat const RowHeight = 88;
NSString * const VideoSegue = @"VideoSegue";

@interface CoachVideoViewController ()

@property (nonatomic, strong) NSArray *coachCategories;

@end

@implementation CoachVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addHeaderRefreshControl];
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self configureLocalization];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.coachCategories.count == 0) {
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)configureLocalization {
    self.title = NSLocalizedString(@"Video Teaching", comment: @"");
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:VideoSegue]) {
        PlayVideoViewController *controller = segue.destinationViewController;
        controller.networkUrlPath = [(CoachVideo *)sender url];
        controller.coachVideoName = [(CoachVideo *)sender name];
    }
}

- (void)addHeaderRefreshControl {
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
        [weakSelf performRequestCoachVideoList];
    }];
}

- (void)performRequestCoachVideoList {
    YFTrainingApi *coachVideoApi = [YFTrainingApi getTrainTennisCoachVideoWithisHDVideo:YES];
    [[YFNetworkingService sharedInstance] sendRequest:coachVideoApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSDictionary *dict = [coachVideoApi responseJSONObject];
            NSArray *videos =  [NSArray modelArrayWithClass:[CoachVideo class] json:dict[@"errDesc"]];
            self.coachCategories = [self filterVideos:videos];
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    }];
}

- (NSArray *)filterVideos:(NSArray *)videos {
    
    NSMutableArray *filterVideoCatecories = [NSMutableArray array];
    NSMutableArray *categoryVideos = [NSMutableArray array];
    
    if (videos.count > 0) {
        for (CoachVideo *coachVideo in videos) {
            if (categoryVideos.count == 0) {
                [categoryVideos addObject:coachVideo];
            }else if ([[categoryVideos.lastObject starName] isEqualToString:coachVideo.starName]) {
                [categoryVideos addObject:coachVideo];
            }else {
                [filterVideoCatecories addObject:categoryVideos.copy];
                categoryVideos = [NSMutableArray array];
                [categoryVideos addObject:coachVideo];
            }
        }
        [filterVideoCatecories addObject:categoryVideos];
    }
    
    return filterVideoCatecories;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.coachCategories.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.coachCategories[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CoachVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoachCell" forIndexPath:indexPath];
    CoachVideo *video = self.coachCategories[indexPath.section][indexPath.row];
    [cell configureCoachVideo:video];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CoachVideo *coachVideo = self.coachCategories[indexPath.section][indexPath.row];
    if ([YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusReachableViaWiFi || [YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
        [self performSegueWithIdentifier:VideoSegue sender:coachVideo];
    }else {
        FUIAlertView *alert = [FUIAlertView alertWithTitle:NSLocalizedString(@"Reminder", comment: "") message:NSLocalizedString(@"Viewing this video under cellular network might result in high data usage.   Proceed / Cancel?", comment: "") cancelTitle:NSLocalizedString(@"Video.Cancel", comment: "") confirmTitle:NSLocalizedString(@"Proceed", comment: "")];
        [alert customizeAppearance];
        [alert setOnOkAction:^{
            [self performSegueWithIdentifier:VideoSegue sender:coachVideo];
        }];
        [alert show];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, HeaderHeight)];
    sectionView.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1];
    UILabel *sectionTitleLabel = [[UILabel alloc] init];
    sectionTitleLabel.font = [UIFont systemFontOfSize:14.0];
    sectionTitleLabel.textColor = [UIColor colorWithWhite:0 alpha:0.6];
    sectionTitleLabel.text = [[self.coachCategories[section] firstObject] starName];
    [sectionTitleLabel sizeToFit];
    [sectionView addSubview:sectionTitleLabel];
    
    sectionTitleLabel.x = 15;
    sectionTitleLabel.y = (sectionView.bounds.size.height - sectionTitleLabel.bounds.size.height) * 0.5;
    
    return sectionView;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[self.coachCategories[section] firstObject] starName];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return HeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return RowHeight;
}

@end
